#include <string.h>
#include <malloc.h>
#include "nbh.h"
#include "../global.h"
#include "../log/log.h"


CLNode_s* NBH_list = NULL;


void NBH_init(void)
{
  NBH_list = CL_create();
  if( NBH_list == NULL )
  {
    LOG_add(LOG_FATAL, "NBH: cannot create the list.");
  }
}

void NBH_destroy(void)
{
  CL_map(NBH_list, free);
  CL_destroy(NBH_list);
}


void NBH_add(neighbour_s* nb)
{
  CLNode_s* node;
  neighbour_s* new_nb;

  node = CL_search_user(NBH_list, (char(*)(void*,void*))NBH_test, nb);
  if( node == NULL )
  {
    new_nb = (neighbour_s*)malloc( sizeof(*new_nb) );
    if( new_nb == NULL )
    {
      LOG_add(LOG_FATAL, "NBH: malloc failed.");
      return;
    }
    memcpy(new_nb, nb, sizeof(*new_nb));

    if( CL_push(NBH_list, new_nb) == NULL )
    {
      LOG_add(LOG_FATAL, "NBH: cannot add a neighbour.");
      return;
    }
  }
}


void NBH_remove(neighbour_s* nb)
{
  CLNode_s* node;

  node = CL_search_user(NBH_list, (char(*)(void*,void*))NBH_test, nb);
  if( node != NULL )
  {
    free(node->data);
    CL_remove(node);
  }
  else
  {
    LOG_add(LOG_WARNING, "NBH: neighbour not found for removal.");
  }
}


inline char NBH_test(neighbour_s* nb1, neighbour_s* nb2)
{
  return ( memcmp(nb1, nb2, sizeof(neighbour_s)) == 0 ) ? 1 : 0;
}

